const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    loading: true,
    error: null,
    localUserInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    serverUserInfo: null,
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },

  onLoad() {
    this.initUserInfo();
  },

  // 初始化用户信息
  async initUserInfo() {
    try {
      const authData = getApp().globalData.authData;
      if (!authData?.token || !authData?.userid) {
        throw new Error('未登录');
      }

      await this.fetchServerUserInfo(authData);
    } catch (error) {
      console.error('初始化用户信息失败:', error);
      this.handleError(error.message || '获取用户信息失败');

      if (error.message === '未登录') {
        wx.redirectTo({
          url: '/pages/auth/auth',
        });
      }
    } finally {
      this.setData({ loading: false });
    }
  },

  // 从服务器获取用户信息
  async fetchServerUserInfo(authData) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://47.94.6.186:3001/api/user/info',
        method: 'GET',
        header: { token: authData.token },
        data: { userid: authData.userid },
        success: (res) => {
          if (res.data?.data?.[0]?.userid) {
            const userData = res.data.data[0];
            this.setData({
              serverUserInfo: {
                ...userData,
                avatar: userData.avatar || defaultAvatarUrl,
                nickname: userData.nickname || userData.username || '未设置昵称'
              },
              hasUserInfo: true
            });
            resolve();
          } else {
            reject(new Error('无效的用户数据'));
          }
        },
        fail: (err) => {
          reject(new Error(err.data?.message || '请求失败'));
        }
      });
    });
  },

  // 处理头像选择
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    this.setData({
      'localUserInfo.avatarUrl': avatarUrl,
      hasUserInfo: this.data.localUserInfo.nickName && avatarUrl !== defaultAvatarUrl,
    });
    this.bindUserAvatar(avatarUrl);
  },

  // 处理昵称输入
  onInputChange(e) {
    const nickName = e.detail.value;
    this.setData({
      'localUserInfo.nickName': nickName,
      hasUserInfo: nickName && this.data.localUserInfo.avatarUrl !== defaultAvatarUrl,
    });
    this.bindUserName(nickName);
  },

  // 绑定头像到服务器
  bindUserAvatar(avatarUrl) {
    if (!this.data.serverUserInfo) return;

    wx.request({
      url: 'http://47.94.6.186:3001/api/user/binduseravatar',
      method: 'POST',
      header: { token: getApp().globalData.authData.token },
      data: {
        userid: getApp().globalData.authData.userid,
        avatar: avatarUrl
      },
      success: () => {
        wx.showToast({ title: '头像更新成功' });
        this.initUserInfo(); // 刷新用户信息
      },
      fail: () => {
        wx.showToast({ title: '头像更新失败', icon: 'error' });
      }
    });
  },

  // 绑定昵称到服务器
  bindUserName(nickName) {
    if (!this.data.serverUserInfo) return;

    wx.request({
      url: 'http://47.94.6.186:3001/api/user/bindusername',
      method: 'POST',
      header: { token: getApp().globalData.authData.token },
      data: {
        userid: getApp().globalData.authData.userid,
        nickname: nickName
      },
      success: () => {
        wx.showToast({ title: '昵称更新成功' });
        this.initUserInfo(); // 刷新用户信息
      },
      fail: () => {
        wx.showToast({ title: '昵称更新失败', icon: 'error' });
      }
    });
  },

  // 错误处理
  handleError(message) {
    this.setData({ error: message });
    wx.showToast({
      title: message,
      icon: 'none'
    });
  },

  // 重新加载
  retryLoad() {
    this.setData({ loading: true, error: null });
    this.initUserInfo();
  }
});